package com.threeti.mecool.core.infrastructure.persistence.acl;

import com.threeti.mecool.core.domain.model.acl.User;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Jay Meng
 */
public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
    User findByloginName(String loginName);

    User findByloginNameAndPassword(String loginName, String password);

    @Transactional(readOnly = true)
    @Query("from User u inner join fetch u.permissionRole.permissionEntries where u.id = ?1")
    User findWithPermissionRoleAndEntries(Long id);

    @Transactional(readOnly = true)
    @Query("from User u inner join fetch u.permissionRole.permissionEntries where u.loginName = ?1")
    User findWithPermissionRoleAndEntries(String loginName);

    @Modifying
    @Transactional
    @Query("update User u set u.password = ?3 where u.loginName = ?1 and u.password = ?2")
    int changePasswordByLoginNameAndOldPassword(String loginName, String oldPassword, String newPassword);

    //@Query("from User where employee.empId = ?1")
    User findByEmployeeEmpId(Long empId);

    List<User> findByPermissionRoleId(Long permRoleId);

    List<User> findByLoginNameIn(List<String> userLoginNameList, Sort sort);
}
